﻿using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Infrastructure.CustomException;

namespace QMERP.Infrastructure.EFCore.Extensions
{
    public static class StockExtension
    {
        /// <summary>
        /// 根据warehouseId和lensId查找stock
        /// </summary>
        /// <param name="query"></param>
        /// <param name="warehouseId"></param>
        /// <param name="lensId"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public static async Task<Stock> GetByWarehouseLens(this IQueryable<Stock> query, long warehouseId, long lensId)
        {
            var stock = await query.Include(x => x.StockDetails).Include(x => x.Warehouse).Include(x => x.Lens).Where(x => x.WarehouseId == warehouseId && x.LensId == lensId).FirstOrDefaultAsync();
            if (stock == null)
                throw new ApiException($"仓库{warehouseId}的镜种{lensId}库存不存在!");
            return stock;
        }
        /// <summary>
        /// 根据warehouseId和lensId查找stock
        /// </summary>
        /// <param name="query"></param>
        /// <param name="warehouseId"></param>
        /// <param name="lensId"></param>
        /// <returns></returns>
        /// <exception cref="ApiException"></exception>
        public static StockDetail GetByRange(this Stock stock, string degreesType, int sph, int cyl)
        {
            var stockDetail = stock.StockDetails.Where(x => x.DegreesType == degreesType && x.SPH == sph && x.CYL == cyl).FirstOrDefault();
            if (stockDetail == null)
                throw new ApiException($"仓库{(stock.Warehouse?.Code)}的销售镜种{(stock.Lens?.SalesLensCode)}度数SPH:{sph},CYL{cyl}不存在");
            return stockDetail;
        }
    }
}
